package com.yijiajiao.finance.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.yijiajiao.finance.bean.*;
import com.yijiajiao.finance.mappers.*;
import com.yijiajiao.finance.service.FinanceLogService;
import com.yijiajiao.finance.service.subaccount.SubAccount;
import com.yijiajiao.finance.service.subaccount.WareSubAccount;
import com.yijiajiao.finance.util.Config;
import com.yijiajiao.finance.util.DateUtil;
import com.yijiajiao.finance.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

import static com.yijiajiao.finance.util.Config.O_PERCENTAGE;
import static com.yijiajiao.finance.util.Config.PERCENTAGE;

/**
 * @AUTHOR zhaoming@eduspace
 * @CREATE 2017-02-21-16:11
 */
@Slf4j
@Service("financeLogService")
public class FinanceLogServiceImpl implements FinanceLogService {

    @Autowired
    private FinanceLogMapper financeLogMapper;
    @Autowired
    private TeacherMoneyMapper teacherMoneyMapper;
    @Autowired
    private WaresSlaveMapper waresSlaveMapper;
    @Autowired
    private SettleAccountsMapper settleAccountsMapper;


    @Override
    @Transactional
    public ResultBean addOrderFinanceLog(FinanceLog financeLog) {
        SubAccount subAccount;
        financeLog.setFinanceLogsType(1);// 表示订单记录
        financeLog.setTradeTime(new Date());
        if (financeLog.getCommodityType() == 1) {
            log.info("课程收入计算-->>");
            subAccount = new WareSubAccount(financeLogMapper, teacherMoneyMapper);
        }else {
            log.info("亿家教平台产品收入计算-->>");
            financeLog.setSystemIncome(financeLog.getTotalPrice());
            subAccount = new SubAccount(financeLogMapper);
        }
        subAccount.subAccount(financeLog);
        log.info("保存的财务记录数据：" + financeLog);
        return ResultBean.getSucResult("保存成功");
    }

    @Override
    @Transactional
    public ResultBean addRefundFinanceLog(FinanceLog financeLog) {
        financeLog.setFinanceLogsType(2);// 表示退款记录
        financeLog.setTrade_no(financeLog.getBatchNo());

        if(financeLog.getCommodityType()==5){
            financeLog.setSystemIncome(BigDecimal.valueOf(0.00).subtract(financeLog.getTotalPrice()));
        }else {

            BigDecimal totalPrice = financeLog.getTotalPrice();
            financeLog.setVariableMoneyChange(BigDecimal.valueOf(0.00).subtract(totalPrice.multiply(PERCENTAGE)));
            financeLog.setTeacherIncome(financeLog.getVariableMoneyChange());
            financeLog.setSystemIncome(BigDecimal.valueOf(0.00).subtract(totalPrice.multiply(O_PERCENTAGE)));
            TeacherMoney teacherMoney = teacherMoneyMapper.queryTeacherMoneyByOpenId(financeLog.getSellOpenId());
            if (teacherMoney == null) throw new RuntimeException("用户("+financeLog.getOpenId()+")信息不存在！");

            teacherMoney.setVariableMoney(teacherMoney.getVariableMoney().add(financeLog.getVariableMoneyChange()));// 日志里存的负值所以直接加
            teacherMoney.setTotalMoney(teacherMoney.getTotalMoney().add(financeLog.getVariableMoneyChange()));
            teacherMoney.setUpdateTime(new Date());
            teacherMoneyMapper.updateTeacherMoney(teacherMoney);
            log.info("修改教师金额账户："+teacherMoney);
            for (WaresSlave ws : financeLog.getWaresSlaves()) {
                ws.setOrderNumber(financeLog.getOrderNumber());
                ws.setCreateTime(new Date());
            }
            waresSlaveMapper.insertWaresSlaves(financeLog.getWaresSlaves());
        }
        financeLogMapper.saveFinanceLog(financeLog);
        log.info("保存数据成功：financeLog===="+financeLog);
        return ResultBean.getSucResult("保存成功！");
    }

    @Override
    public ResultBean queryTeacherTradeLogs(FinanceLogQuery flq) {
        List<FinanceBean> financeBeans = new ArrayList<>();
        //通过手机号查询openId
        log.info("通过手机号查询openId-->");
        String httpRest = HttpUtil.httpRest("http://" + Config.getString("user_server"),
                            Config.getString("user.userInfoByPhone") + "phone=" + flq.getPhoneNum(),
                            null, null, "GET");
        UserInfoBean userInfoBean = JSON.parseObject(httpRest).getObject("result", UserInfoBean.class);

        BigDecimal totalIncome = new BigDecimal("0.00");//收入总和
        BigDecimal totalRefund = new BigDecimal("0.00");//退款总和
        BigDecimal totalTeacherIncome = new BigDecimal("0.00"); //教师部分总和
        BigDecimal totalSytemIncome = new BigDecimal("0.00");//平台总和

        flq.setOpenId(userInfoBean.getUserOpenId());
        List<FinanceLog> conditions = financeLogMapper.queryTeacherTradeLogs(flq);
        for(FinanceLog fl :conditions){
            FinanceBean financeBean = new FinanceBean();
            financeBean.setTeacherName(userInfoBean.getName());
            financeBean.setOpenId(fl.getSellOpenId());
            financeBean.setTeacherPhoneNum(fl.getTeacherPhoneNum());
            financeBean.setStudentPhoneNum(fl.getStudentPhoneNum());
            financeBean.setTradeTime(fl.getTradeTime());
            financeBean.setOrderNumber(fl.getOrderNumber());
            financeBean.setTrade_no(fl.getTrade_no());
            financeBean.setCurriculumName(fl.getCurriculumName());
            financeBean.setTotalPrice(fl.getTotalPrice());
            if(fl.getCurriculumCount()>0){//
                financeBean.setSinglePrice(fl.getTotalPrice().divide(new BigDecimal(fl.getCurriculumCount()), 2, BigDecimal.ROUND_HALF_EVEN));
            }
            financeBean.setTradeType(fl.getTradeType() == null?"":TradeType.getName(fl.getTradeType()));
            financeBean.setCurriculumType(fl.getCurriculumType() == null?"":CurriculumType.getName(fl.getCurriculumType()));
            financeBean.setTeacherIncome(fl.getTeacherIncome());
            financeBean.setSystemIncome(fl.getSystemIncome());
            if(fl.getFinanceLogsType()==1){
                totalIncome=totalIncome.add(fl.getTotalPrice());
            }else if(fl.getFinanceLogsType()==2){
                totalRefund=totalRefund.subtract(fl.getTotalPrice());
                financeBean.setTotalPrice(fl.getTotalPrice().multiply(new BigDecimal(-1)));
            }
            financeBean.setFinanceLogsType(fl.getFinanceLogsType());
            totalTeacherIncome=totalTeacherIncome.add(fl.getTeacherIncome());
            totalSytemIncome=totalSytemIncome.add(fl.getSystemIncome());
            System.out.println("totalIncome="+totalIncome+",totalRefund="+totalRefund+",totalTeacherIncome="+totalTeacherIncome+",totalSystemIncome="+totalSytemIncome);
            financeBeans.add(financeBean);
        }
        if(flq.getRay()==0){
            Collections.sort(financeBeans, new sortByDateDesc0());
        }else{
            Collections.sort(financeBeans, new sortByDateDesc1());
        }
        FinanceBean financeBean = new FinanceBean();
        System.out.println("totalIncome="+totalIncome+",totalRefund="+totalRefund+",totalTeacherIncome="+totalTeacherIncome+",totalSystemIncome="+totalSytemIncome);
        financeBean.setTotalIncome(totalIncome);
        financeBean.setTotalRefund(totalRefund);
        financeBean.setTotalTeacherIncome(totalTeacherIncome);
        financeBean.setTotalSytemIncome(totalSytemIncome);
        financeBeans.add(financeBean);
        return ResultBean.getSucResult(financeBeans);
    }

}

//时间降序
class sortByDateDesc0 implements Comparator {
    @Override
    public int compare(Object o1, Object o2) {
        FinanceBean fb1 = (FinanceBean) o1;
        FinanceBean fb2 = (FinanceBean) o2;
        return fb1.getTradeTime().compareTo(fb2.getTradeTime());
    }
}

//时间升序
class sortByDateDesc1 implements Comparator{
    @Override
    public int compare(Object o1, Object o2) {
        FinanceBean fb1 = (FinanceBean) o1;
        FinanceBean fb2 = (FinanceBean) o2;
        return -fb1.getTradeTime().compareTo(fb2.getTradeTime());
    }
}

enum CurriculumType{
    LiveOneTOone(1, "一对一直播课"),
    LiveVedio(2, "视频课"),
    LiveSmallClass(3,"小班直播课"),
    LiveBigClass(4, "大班直播课");

    private int index;
    private String name;

    CurriculumType(int index, String name) {
        this.index =  index;
        this.name = name;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public static String getName(int index){
        switch (index){
            case 1: return LiveOneTOone.name;
            case 2: return LiveVedio.name;
            case 3: return LiveSmallClass.name;
            case 4: return LiveBigClass.name;
            default: return null;
        }
    }
}

enum TradeType{
    AliPay(1, "支付宝"),
    WeixinPay(2, "微信"),
    Free(3, "免费");

    private int index;
    private String name;

    TradeType(int index, String name) {
        this.index = index;
        this.name = name;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public static String getName(int index){
        switch (index){
            case 1: return AliPay.name;
            case 2: return WeixinPay.name;
            case 3: return Free.name;
            default: return null;
        }
    }
}